package org.apache.struts2.plugin.json.reflection;

import java.lang.reflect.Array;
import java.util.Iterator;
import org.apache.struts2.plugin.json.model.JSONArray;
import org.apache.struts2.plugin.json.model.JSONValue;

/**
 * @author VERDOÏA Laurent <verdoialaurent@gmail.com>
 */
public abstract class JSONArrayReflection {

    public static JSONArray reflection(Object o) throws JSONReflectionException {
        if (o.getClass().isArray() == true) {
            return fromArray((Object[]) o);
        } else if (o instanceof Iterable) {
            return fromIterable((Iterable<? extends Object>) o);
        }
        return null;
    }

    public static JSONArray fromArray(Object[] o) throws JSONReflectionException {
        JSONArray j = new JSONArray();

        for (int i = 0,  length = Array.getLength(o); i < length; i++) {
            JSONValue data = Reflection.reflection(Array.get(o, i));
            j.addData(data);
        }

        return j;
    }

    public static JSONArray fromIterable(Iterable<? extends Object> o) throws JSONReflectionException {
        JSONArray array = new JSONArray();

        Object rawData;
        for (Iterator<? extends Object> i = o.iterator(); i.hasNext();) {
            rawData = i.next();
            JSONValue data = Reflection.reflection(rawData);
            array.addData(data);
        }

        return array;
    }
}
